const Blog = require('../db/modules/Blog')
const getList = async ({ author, keyword }) => {
  let whereOption = {}
  if (author) {
    whereOption.author = author
  }
  if (keyword) {
    whereOption.title = new RegExp(keyword, 'i')
  }
  const res = await Blog.find(whereOption)
  console.log(res, '---- 查询博客列表 ----')
  return res
}
const getDetail = async (id) => {
  const res = await Blog.findById(id)
  return res
}

const newBlog = async (blogData = {}) => {
  // 写法一
  // const { title, content, author } = blogData
  // let res = await Blog.create({ title, content, author })
  // 写法二
  let res = new Blog(blogData)
  res = await res.save()
  if (res) {
    return blogData
  } else {
    return false
  }
}

const updateBlog = async (id, blogData = {}) => {
  const { title, content, author } = blogData
  let res = await Blog.findByIdAndUpdate(
    id,
    { title, content, author },
    { new: true }
  )
  if (res) {
    return blogData
  } else {
    return false
  }
}

const delBlog = async (id) => {
  // 先练习真删除，实战中基本都输软删除，即数据库改变state状态为0,查询数据时只查询state=1的数据
  let res = await Blog.findByIdAndDelete(id)
  return res
}

module.exports = {
  getList,
  getDetail,
  newBlog,
  updateBlog,
  delBlog,
}
